package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.PageResult;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Menu;
import com.xrit.sunnyday.pojo.MenuExtend;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.service.MenuService;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜单管理
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private UserService userService;

    @Reference
    private MenuService menuService;


    /**
     * 动态菜单查询
     * @return
     */
    @GetMapping("/getMenu")
    public Result getMenu(){
        //1.从SecurityContextHolder中获取id
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //2.获取用户名
        String userr = user.getUsername();
        //3.根据用户名查用户信息                        通过用户id查询选中的角色id
        com.xrit.sunnyday.pojo.User user1 = userService.findByUsername(userr);
        //4.取出角色id
        Set<Role> roles = user1.getRoles();
        //5.for角色 根据角色id获取角色对应的菜单
        List<Menu> menus = null;
        for (Role role:roles) {
            menus = menuService.findByRoid(role.getId());
        }
        //返回
        return new Result(true,MessageConstant.GET_MENU_SUCCESS,menus);
    }

    /**
     * 查询全部菜单及子菜单
     * @return
     */
    @GetMapping("/QueryMenuAll")
    public Result QueryMenuAll(){
        List<MenuExtend> menuExtends = menuService.QueryMenuAll();
        Result result = new Result(true, "查询菜单成功",menuExtends);
        return result;
    }

}
